package com.zhanglu.fun.tookit.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author zhanglu
 * @description
 * @date 2017/10/23 22:46
 */
public class OldJwtUtil {
    public static String secret = "fun-auth-info"; // key暂时不加密，由字符串代替

    /**
     * 创建jwt加密字符串token
     * @param tokenInfo
     * @return
     * @throws Exception
     */
    public static String createJWT(TokenInfo tokenInfo) {
        return Jwts.builder()
                .setSubject(tokenInfo.getNickName())
                .setIssuer("Fun_ZL")
                //.setIssuedAt(tokenInfo.getCreateDate())
                //.setExpiration(tokenInfo.getExpiresDate())
                .claim("createDate", tokenInfo.getCreateDate())
                .claim("expiresDate", tokenInfo.getExpiresDate())
                .claim("nickName", tokenInfo.getNickName())
                .claim("email", tokenInfo.getEmail())
                .claim("roles", tokenInfo.getRoles())
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    /**
     * 解密jwt
     *
     * @param jwt
     *
     * @return
     */
    public static TokenInfo parseJWT(String jwt) {
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(jwt).getBody();
        return new TokenInfo()
                .setNickName(claims.get("nickName",String.class))
                .setEmail(claims.get("email",String.class))
                .setRoles(claims.get("roles",String.class))
                .setCreateDate(claims.get("createDate",Date.class))
                .setExpiresDate(claims.get("expiresDate",Date.class));
        // .setCreateDate(claims.getIssuedAt()) // 创建时间
        // .setExpiresDate(claims.getExpiration());// 过期时间
    }
}
